<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="匹配关键词" prop="matchValue" label-width="90px">
        <el-input
          v-model="queryParams.matchValue"
          placeholder="请输入匹配的关键词、事件等"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wx:msgReplyRule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx:msgReplyRule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:msgReplyRule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx:msgReplyRule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="msgReplyRuleList" border type="expand"  @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="作用范围">
              <span>{{ scope.row.appid?'当前公众号':'全部公众号' }}</span>
            </el-form-item>
            <el-form-item label="精确匹配">
              <span>{{ scope.row.exactMatch?'是':'否' }}</span>
            </el-form-item>
            <el-form-item label="是否有效">
              <span>{{ scope.row.status?'是':'否' }}</span>
            </el-form-item>
            <el-form-item label="备注说明">
              <span>{{ scope.row.desc }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="匹配关键词" align="center" prop="matchValue" />
      <el-table-column label="回复消息类型" align="center" prop="replyType" :formatter="replyTypeFormat"/>
      <el-table-column label="回复消息内容" align="center" prop="replyContent" show-overflow-tooltip/>
      <el-table-column label="生效起始时间" align="center" prop="effectTimeStart" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.effectTimeStart }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生效结束时间" align="center" prop="effectTimeEnd" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.effectTimeEnd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规则优先级" align="center" prop="priority" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx:msgReplyRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:msgReplyRule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自动回复规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="匹配关键词" prop="matchValue">
          <tags-editor v-model="form.matchValue"></tags-editor>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作用范围" prop="appid">
              <el-select v-model="form.appid" placeholder="作用范围">
                <el-option label="全部公众号" value=""></el-option>
                <el-option label="当前公众号" :value="selectedAppid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="精确匹配" prop="exactMatch">
              <el-switch v-model="form.exactMatch" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="回复类型" prop="replyType">
              <el-select v-model="form.replyType" @change="onReplyTypeChange">
                <el-option v-for="(name,key) in KefuMsgType" :key="key" :value="key" :label="name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生效时间" prop="effectTimeStart">
              <el-time-picker v-model="form.effectTimeStart" value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="effectTimeEnd">
              <el-time-picker v-model="form.effectTimeEnd" value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="回复内容" prop="replyContent">
          <el-input v-model="form.replyContent" type="textarea" :rows="5" placeholder="文本、图文ID、media_id、json配置"></el-input>
          <el-button type="text" v-show="'text'==form.replyType" @click="addLink">插入链接</el-button>
          <el-button type="text" v-show="assetsType" @click="assetsSelectorVisible=true">
            从素材库中选择<span v-if="'miniprogrampage'==form.replyType || 'music'==form.replyType">缩略图</span>
          </el-button>
        </el-form-item>
        <el-form-item label="备注说明" prop="desc">
          <el-input v-model="form.desc" placeholder="备注说明"></el-input>
        </el-form-item>
        <el-form-item label="规则优先级" prop="priority">
          <el-input-number v-model="form.priority" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <assets-selector v-if="assetsSelectorVisible && assetsType" :visible="assetsSelectorVisible" :selectType="assetsType" @selected="onAssetsSelect" @onClose="assetsSelectorVisible=false"></assets-selector>
    </el-dialog>
  </div>
</template>

<script>
import { listMsgReplyRule, getMsgReplyRule, delMsgReplyRule, addMsgReplyRule, updateMsgReplyRule } from "@/api/wx/msgReplyRule";
import TagsEditor from '@/components/tags-editor'
import AssetsSelector from '../assets/assets-selector'
import { mapState } from 'vuex'
export default {
  name: "MsgReplyRule",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自动回复规则表格数据
      msgReplyRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appid: undefined,
        ruleName: undefined,
        matchValue: undefined,
        exactMatch: undefined,
        replyType: undefined,
        replyContent: undefined,
        status: undefined,
        desc: undefined,
        effectTimeStart: undefined,
        effectTimeEnd: undefined,
        priority: undefined,
      },
      assetsSelectorVisible:false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        matchValue: [
          { required: true, message: "匹配的关键词、事件等不能为空", trigger: "blur" }
        ],
        replyType: [
          { required: true, message: "回复消息类型不能为空", trigger: "change" }
        ],
        replyContent: [
          { required: true, message: "回复消息内容不能为空", trigger: "blur" }
        ],
        effectTimeStart: [
          { required: true, message: "生效起始时间不能为空", trigger: "blur" }
        ],
        effectTimeEnd: [
          { required: true, message: "生效结束时间不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "规则优先级不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    TagsEditor, AssetsSelector
  },
  computed: mapState({
    KefuMsgType: state=>state.message.KefuMsgType,
    selectedAppid:state=>state.wxAccount.selectedAppid,
    assetsType(){
      const config={//消息类型与选择素材类型对应关系
        'image':'image',
        'voice':'voice',
        'video':'video',
        'mpnews':'news',
        'miniprogrampage':'image',//小程序需选择卡片图
        'music':'image'
      }
      return config[this.form.replyType] || ''
    }
  }),
  created() {
    this.getList();
  },
  methods: {
    /** 查询自动回复规则列表 */
    getList() {
      this.loading = true;
      listMsgReplyRule(this.queryParams).then(response => {
        this.msgReplyRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: undefined,
        appid: undefined,
        ruleName: undefined,
        matchValue: undefined,
        exactMatch: undefined,
        replyType: undefined,
        replyContent: undefined,
        status: undefined,
        desc: undefined,
        effectTimeStart: undefined,
        effectTimeEnd: undefined,
        priority: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自动回复规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const ruleId = row.ruleId || this.ids
      getMsgReplyRule(ruleId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改自动回复规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.ruleId != null) {
            updateMsgReplyRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMsgReplyRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除自动回复规则编号为"' + ruleIds + '"的数据项？').then(() => {
        this.loading = true;
        return delMsgReplyRule(ruleIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wx/msgReplyRule/export', {
        ...this.queryParams
      }, `msgReplyRule_${new Date().getTime()}.xlsx`)
    },
    onAssetsSelect(assetsInfo){
      if(this.form.replyType=='miniprogrampage' || this.form.replyType=='music'){
        let data = JSON.parse(this.form.replyContent)
        if(data && data.thumb_media_id)data.thumb_media_id=assetsInfo.mediaId
        this.form.replyContent = JSON.stringify(data, null, 4)
      }else{
        this.form.replyContent = assetsInfo.mediaId
      }
      this.assetsSelectorVisible=false
    },
    replyTypeFormat(row, column, cellValue) {
      return this.KefuMsgType[cellValue];
    },
    onReplyTypeChange(value) {
      if ("miniprogrampage" == value) {
        let demo = { title: "标题", appid: "小程序APPID", pagepath: "页面地址", thumb_media_id: "缩略图media_id" };
        this.form.replyContent = JSON.stringify(demo, null, 4)
      } else if ("music" == value) {
        let demo = { musicurl: "音乐链接", hqmusicurl: "高品质链接", title: "标题", description: "描述", thumb_media_id: "缩略图media_id" }
        this.form.replyContent = JSON.stringify(demo, null, 4)
      } else if ("msgmenu" == value) {
        let demo = { head_content: "开头文字", list: [{ id: "菜单1ID", content: "菜单2内容" }, { id: "菜单2ID", content: "菜单2内容" }, { id: "菜单nID", content: "菜单n内容" }], tail_content: "结尾文字" }
        this.form.replyContent = JSON.stringify(demo, null, 4)
      } else if ("news" == value) {
        let demo={title:"文章标题",description:"文章简介",url:"链接URL",picUrl:"缩略图URL"}
        this.form.replyContent = JSON.stringify(demo, null, 4)
      } else {
        this.form.replyContent = '媒体素材media_id'
      }
    },
    addLink() {
      this.form.replyContent += '<a href="链接地址">链接文字</a>'
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
